package nl.siegmann.epublib.epub;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Resources;
import nl.siegmann.epublib.domain.TableOfContents;
import nl.siegmann.epublib.service.MediatypeService;
import nl.siegmann.epublib.util.ResourceUtil;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Simple2 {
	private static Logger log = Logger.getLogger("测试读取epub");
	public static void main(String[] args) throws SAXException, ParserConfigurationException {
		try {
			Book readBook = new EpubReader().readEpub(new FileInputStream("F:/南海.epub"));
			
			log.log(Level.INFO, "开始读取内容3");
			//取内容
			List<Resource> contents = readBook.getContents();
			InputStream content = contents.get(0).getInputStream();
			createFile(contents.get(0).getHref(), content);
			log.log(Level.INFO, "结束读取内容");
			
			log.log(Level.INFO, "开始读取静态css资源");
			Resources opfResources = readBook.getResources();
			List<Resource> cssResources = opfResources.getResourcesByMediaType(MediatypeService.CSS);
			createFile(cssResources.get(0).getHref(), cssResources.get(0).getInputStream());
			log.log(Level.INFO, "结束读取静态css资源");
			
			log.log(Level.INFO, "开始读取静态图片资源");
			List<Resource> imgResources = opfResources.getResourcesByMediaType(MediatypeService.JPG);
			createFile(imgResources.get(0).getHref(), imgResources.get(0).getInputStream());
			log.log(Level.INFO, "结束读取静态图片资源");
			
			log.log(Level.INFO, "开始读取");
			TableOfContents ncxResource = readBook.getTableOfContents();

		} catch (FileNotFoundException e) {
			log.log(Level.SEVERE,"FileNotFoundException");
		} catch (IOException e) {
			log.log(Level.SEVERE,"IOException");
		}
	}
	
	public static void createFile(String fileName, InputStream in){
		try(OutputStream contentOut = new FileOutputStream("F:/" + fileName)){
			byte[] contentBytes = new byte[in.available()];
			in.read(contentBytes);
			contentOut.write(contentBytes);
			contentOut.close();
		} catch (FileNotFoundException e) {
			log.log(Level.SEVERE,"FileNotFoundException");
		} catch (IOException e) {
			log.log(Level.SEVERE,"IOException");
		}
	}
}
